<!--
 * @Description: 
 * @Author: shizhe
 * @Date: 2021-12-03 14:07:45
 * @LastEditTime: 2022-01-18 15:04:34
 * @LastEditors: shizhe
 * @Reference: 
-->
<template>
  <div>
    <el-tooltip :disabled="disabledTooltip" effect="light" :content="value" placement="top">
      <el-input
        :value="value"
        @input="deviationContentChange"
        :placeholder="placeholder"
        :size="size"
        class="inputWidth"
      >
      </el-input>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  props: {
    size: {
      type: String,
      default: 'mini'
    },
    deviationContent: {
      type: [String, Number],
      require: true
    },
    placeholder: {
      type: String,
      default: '请输入偏差内容'
    }
  },
  data() {
    return {
      disabledTooltip: true,
      value: ''
    }
  },
  watch: {
    deviationContent(val) {
      this.value = val
      this.regText(val)
    }
  },
  mounted() {
    if (!this.deviationContent) {
      return false
    }
    this.regText(this.deviationContent)
  },
  methods: {
    regText(val) {
      this.value = val
      this.$emit('input', val)
      // 获取当前组件的input宽度
      const el = document.querySelector('.inputWidth').clientWidth
      // 匹配汉字的正则
      const reg = /[\u4e00-\u9fa5]/
      // 防止输入数字出现报错
      const arr = (val + '').split('')
      let textWidth = 0
      arr.forEach(item => {
        // 文字宽度为16，其余为8
        if (reg.test(item)) {
          textWidth += 16
        } else {
          textWidth += 8
        }
      })
      // 如果文本的宽度大于input框的宽度，则显示tooltip
      if (textWidth > el) {
        this.disabledTooltip = false
      } else {
        this.disabledTooltip = true
      }
    },
    deviationContentChange(val) {
      this.regText(val)
    }
  }
}
</script>
<style lang="less" scoped></style>
